﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;



public partial class Inventory_MasterPage : System.Web.UI.MasterPage
{
    protected DataTable dt;
    protected Mode EditMode;
    protected int ListID;
    protected int EditRowIdx = -1;
    protected InventoryListBZ ListBz;

    protected void Page_Load(object sender, EventArgs e)
    {
        //load business logic
        ListBz = InventoryListBZ.GetInventoryListBZ(this.Page.Title);
        LabelListName.Text = ListBz.LabelListName;
        LabelDate.Text = ListBz.LabelDate;
        LabelListNumber.Text = ListBz.LabelListNumber;
        ButtonSave.Text = ListBz.ButtonSave;
        ButtonClose.Text = ListBz.ButtonClose;

        if (!IsPostBack)
        {
            if (null != Request.QueryString["ListID"])
            {
                ListID = int.Parse(Request.QueryString["ListID"]);
                int warehouseid;
                DateTime date;
                string listnumber;
                ListBz.GetListData(ListID,out dt,out warehouseid,out date, out listnumber);
                TextBoxDate.Text = date.ToString("yyyy-MM-dd");
                TextBoxListNumber.Text = listnumber;
            }
            else
            {
                ListID = 0;
                dt = ListBz.GetEmptyList();
                
            }
            ShowData();
            EditMode = Mode.Empty;
            ViewState["ListID"] = ListID;
            ViewState["DataSource"] = dt;
            ViewState["Mode"] = EditMode;

            //disable item edit
            SetButtonbyMode(EditMode);
        }
        else
        {
            ListID = (int)ViewState["ListID"];
            dt = (DataTable)ViewState["DataSource"];
            EditMode = (Mode)ViewState["Mode"];
            if (Mode.Edit == EditMode)
            {
                EditRowIdx = (int)ViewState["EditRowIdx"];
            }
        }

    }


    void ShowData()
    {
        string[] keys = { "ProductID" };
        //show the general information

        //show the detail informations
        GridViewDetail.DataSource = dt;
        GridViewDetail.DataKeyNames = keys;
        GridViewDetail.DataBind();
    }

    protected void ButtonAddNew_Click(object sender, EventArgs e)
    {
        EditMode = Mode.AddNew;
        ViewState["Mode"] = EditMode;
        ClearItemEditRegion();
        //enable item edit
        SetButtonbyMode(EditMode);
    }

    void ClearItemEditRegion()
    {
        this.HiddenProductID.Value = string.Empty;
        this.TextBoxProductCode.Text = string.Empty;
        this.TextBoxProductModule.Text = string.Empty;
        this.TextBoxProductName.Text = string.Empty;
        this.TextBoxQuantity.Text = string.Empty;
        this.TextBoxColor.Text = string.Empty;
    }

    protected void ButtonSaveItem_Click(object sender, EventArgs e)
    {
        SaveItem();
        ViewState["DataSource"] = dt;
        EditMode = Mode.Edit;
        ViewState["Mode"] = EditMode;
        //enable item edit
        SetButtonbyMode(EditMode);

        ShowData();
    }

    protected void ButtonSave_AddNew_Click(object sender, EventArgs e)
    {
        SaveItem();
        ViewState["DataSource"] = dt;
        EditMode = Mode.AddNew;
        ViewState["Mode"] = EditMode;
        //enable item edit
        SetButtonbyMode(EditMode);
        ClearItemEditRegion();

        ShowData();
    }

    void SaveItem()
    {
        LabelError.Text = "";
        int productid;
        string productname, productmodule, productcolor;
        ListBz.GetProductInfo(TextBoxProductCode.Text.Trim(), out productid, out productname, out productmodule, out productcolor);
        if (productid > 0)
        {
            HiddenProductID.Value = productid.ToString();
            TextBoxProductName.Text = productname;
            TextBoxProductModule.Text = productmodule;
            TextBoxColor.Text = productcolor;
        }
        else
        {
            LabelError.Text = "没有找到这个产品编码对应的产品！";
            return;
        }
        decimal quantity = 0;
        try
        {
            quantity = decimal.Parse(TextBoxQuantity.Text.Trim());
        }
        catch
        {
            LabelError.Text = "数量不合法！";
            return;
        }

        DataRow dr = AddNewRow(int.Parse(HiddenProductID.Value.ToString()),
                    TextBoxProductCode.Text.Trim(),
                    TextBoxProductName.Text.Trim(),
                    TextBoxProductModule.Text.Trim(),
                    TextBoxColor.Text.Trim(),
                    quantity);
        if (Mode.AddNew == EditMode)
        {
            dt.Rows.Add(dr);
            ViewState["EditRowIdx"] = dt.Rows.Count - 1;
        }
        else if (Mode.Edit == EditMode)
        {
            dt = SystemFunction.ReplaceRow(dt, dr, EditRowIdx);
            ViewState["EditRowIdx"] = EditRowIdx;
        }
    }

    DataRow AddNewRow(int id, string code, string name, string module, string color, decimal quantity)
    {
        DataRow dr = dt.NewRow();
        dr["ProductID"] = id;
        dr["ProductCode"] = code;
        dr["ProductName"] = name;
        dr["ProductModule"] = module;
        dr["ProductColor"] = color;
        dr["Quantity"] = quantity;
        return dr;
    }

    
    protected void GridViewDetail_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index;
        switch (e.CommandName)
        {
            case "DeleteItem":
                index = PublicDefine.GetSelectRowIndex(e);
                EditMode = Mode.Empty;
                ViewState["Mode"] = EditMode;
                //enable item edit
                SetButtonbyMode(EditMode);
                //delete the selected row
                dt.Rows.Remove(dt.Rows[index]);
                ShowData();
                break;

            case "EditItem":
                index = PublicDefine.GetSelectRowIndex(e);
                EditMode = Mode.Edit;
                ViewState["Mode"] = EditMode;
                EditRowIdx = index;
                ViewState["EditRowIdx"] = EditRowIdx;
                //enable item edit
                SetButtonbyMode(EditMode);
                //set textbox
                HiddenProductID.Value = dt.Rows[index]["ProductID"].ToString();
                TextBoxProductCode.Text = dt.Rows[index]["ProductCode"].ToString();
                TextBoxQuantity.Text = dt.Rows[index]["Quantity"].ToString();
                break;
        }
    }

    void SetButtonbyMode(Mode mode)
    {
        if (Mode.Empty == mode)
        {
            ButtonSave_AddNew.Enabled = false;
            ButtonSaveItem.Enabled = false;
            ButtonCancle.Enabled = false;
        }
        else
        {
            ButtonSave_AddNew.Enabled = true;
            ButtonSaveItem.Enabled = true;
            ButtonCancle.Enabled = true;
        }
    }

    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        Save();
    }

    virtual protected bool CheckList()
    {
        LabelError.Text = "";
        bool result = false;

        if (0 == TextBoxListNumber.Text.Trim().Length)
        {
            LabelError.Text = "单号未填写";
            return result;
        }
        DateTime date;
        try
        {
            date = DateTime.Parse(TextBoxDate.Text.Trim());
        }
        catch
        {
            LabelError.Text = "时间不合法";
            return result;
        }
        if (0 == dt.Rows.Count)
        {
            LabelError.Text = "没有明细项！";
            return result;
        }
        return true;
    }

    void Save()
    {
        using (SqlConnection connect = new SqlConnection(PublicDefine.SQLConnectString))
        {

            connect.Open();
            SqlTransaction tran = connect.BeginTransaction();
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connect;
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.StoredProcedure;

                // add new list
                if (0 == ListID)
                {
                    if (!CheckList())
                    {
                        return;
                    }
                    ListID = AddList(cmd);
                }
                else //update list
                {
                    if (!CheckList())
                    {
                        return;
                    }
                    //delete the old list and add a new list
                    DeleteList(cmd);
                    ListID = AddList(cmd);

                }
                tran.Commit();
                connect.Close();
            }
            catch (Exception ex)
            {
                LabelError.Text = "保存失败！";
                tran.Rollback();
            }
        }
        ViewState["ListID"] = ListID;
    }
    
    virtual protected int AddList(SqlCommand cmd)
    {
        int warehouseid = int.Parse(this.DropDownListWarehouse.SelectedValue);
        DateTime createddate = DateTime.Parse(TextBoxDate.Text.Trim());
        string listnumber = TextBoxListNumber.Text.Trim();

        return ListBz.AddList(cmd, warehouseid, createddate,listnumber, dt);
    }

    virtual protected void DeleteList(SqlCommand cmd)
    {
        ListBz.DeleteList(cmd, ListID);
    }

    protected void ButtonCancle_Click(object sender, EventArgs e)
    {

    }
    protected void ButtonClose_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewInventory.aspx");
    }
}
